package com.wss.lsl.lucene.demo.shipin.advanced.query;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class FileIndexUtils {

	private static Directory directory;

	static {
		try {
			File dir = new File("d:\\lucene\\files\\index");
			if (!dir.exists()) {
				dir.mkdirs();
			}
			directory = FSDirectory.open(dir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Directory getDirectory() {
		return directory;
	}

	public static void index(boolean hasNew) {

		IndexWriter writer = null;
		try {
			writer = new IndexWriter(directory, new IndexWriterConfig(
					Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));
			if (hasNew) {
				writer.deleteAll();
			}
			File file = new File("E:\\jteach\\test");
			Document doc = null;
			Random random = new Random();
			int index = 0;
			for (File f : file.listFiles()) {
				if (f.isFile()) {
					doc = new Document();
					doc.add(new Field("id", String.valueOf(index++),
							Field.Store.YES, Field.Index.NOT_ANALYZED));
					doc.add(new Field("content", new FileReader(f)));
					doc.add(new Field("filename", f.getName(), Field.Store.YES,
							Field.Index.NOT_ANALYZED));
					doc.add(new Field("path", f.getAbsolutePath(),
							Field.Store.YES, Field.Index.NOT_ANALYZED));
					doc.add(new NumericField("date", Field.Store.YES, true)
							.setLongValue(f.lastModified()));
					doc.add(new NumericField("size", Field.Store.YES, true)
							.setLongValue(f.length()));
					doc.add(new NumericField("score", Field.Store.YES, true)
							.setIntValue(random.nextInt(600)));
					writer.addDocument(doc);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("indexed done!");
	}

}
